package IntelSpam::Filters::LoggingFilter;

use 1.0;

use strict;
use warnings;

use MIME::Parser;
use IntelSpam::Config;
use Data::Dumper;
use Log::Log4perl qw(get_logger);

our $VERSION = '1.0';
our $DEBUG = 1;

our $REGISTER = ['header', 'body'];
our $META = {
	'id' => 'logging_filter',
	'name' => 'Logging Filter',
	'description' => 'Do nothing but watching email\'s subject',
	'version' => '1.0',
	'weight' => 0
	
};

our $logger = get_logger("LoggingFilter");
our $CFG = {};

sub new($){
	bless {}, shift;
}

sub filter_header($$$$){
	my $this = shift;
	my $ctx = shift;
	my $key = shift;
	my $value = shift;

	$logger->info("LoggingFilter: $key: $value");
	0;
}

sub filter_body($$$){
	my ($this, $ctx, $entity) = @_;
	dump_entity($entity);
	0;
}

sub dump_entity {
    my ($entity, $name) = @_;
    defined($name) or $name = "'anonymous'";
    my $IO;

    # Output the head:
    $logger->info('=' x 60);
    $logger->info("Message $name: ");
    $logger->info('=' x 60);
    $logger->info($entity->head->original_text);
    

    # Output the body:
    my @parts = $entity->parts;
    if (@parts) {                     # multipart...
	my $i;
	foreach $i (0 .. $#parts) {       # dump each part...
	    dump_entity($parts[$i], ("$name, part ".(1+$i)));
	}
    }
    else {                            # single part...	

	# Get MIME type, and display accordingly...
	my ($type, $subtype) = split('/', $entity->head->mime_type);
	my $body = $entity->bodyhandle;
	
	if ($type =~ /^(text|message)$/) {     # text: display it...
	    if ($IO = $body->open("r")) {
		$logger->info($_) while (defined($_ = $IO->getline));
		$IO->close;
	    }
	    else {       # d'oh!
		$logger->error("$0: couldn't find/open '$name': $!");
	    }
	}
	else {                                 # binary: just summarize it...
	    my $path = $body->path;
	    my $size = ($path ? (-s $path) : '???');
	    $logger->info(">>> This is a non-text message, $size bytes long.");
	    $logger->info(">>> It is stored in ". ($path ? "'$path'" : 'core'));
	}
    }
    1;
}

sub get_registers($){
	$REGISTER;
}

sub get_meta($){
	$META;
}

sub set_cfg($$){
	my $this = shift;
	$CFG = shift;
}
